#!/bin/sh /etc/rc.common
# Copyright (C) 2013-2014 OpenWrt.org
# Copyright (C) 2018-2020 Tano Systems LLC

START=00
STOP=90

HWCLOCK=/sbin/hwclock

extra_command "systohc" "Save system time to hardware RTC"
extra_command "hctosys" "Load system time from hardware RTC"

LOG="logger -t sysfixtime -p"

boot() {
	hwclock_call restore

	local maxtime="$(get_maxtime)"
	local curtime="$(date +%s)"
	if [ $curtime -lt $maxtime ]; then
		date -s @$maxtime
		hwclock_call save
	fi
}

apply_timezone() {
	local config="$1"
	local zonename

	config_get zonename "$config" 'zonename' ''

	[ -n "$zonename" ] && [ -f "/usr/share/zoneinfo/$zonename" ] && \
		ln -sf "/usr/share/zoneinfo/$zonename" /tmp/localtime

	# apply timezone to kernel
	hwclock -u --systz
}

hwclock_call() {
	local args rtc_dev kept_in_localtime

	config_load 'system'
	config_get rtc_dev 'rtc' 'hwclock_dev' '/dev/rtc0'
	config_get_bool kept_in_localtime 'rtc' 'hwclock_localtime' 1

	args=""

	if [ "$kept_in_localtime" = "0" ]; then
		# -u|--utc
		append args "-u" " "
	else
		# -l|--localtime
		append args "-l" " "

		# Early apply timezone from system configuration
		# if we keep time in hardware clock in localtime
		config_foreach apply_timezone system
	fi

	# -f|--rtc
	append args "-f $rtc_dev" " "

	if [ "$1" = "save" ]; then
		# -w|--systohc
		append args "-w" " "
	elif [ "$1" = "restore" ]; then
		# -s|--hctosys
		append args "-s" " "
	fi

	RET="0"
	if [ ! -e "$rtc_dev" ]; then
		RET="no $rtc_dev device"
	elif [ ! -e "$HWCLOCK" ]; then
		RET="no $HWCLOCK"
	else
		$HWCLOCK $args
		RET="$?"
	fi

	if [ "$1" = "save" ]; then
		if [ "$RET" = "0" ]; then
			$LOG daemon.info "saved localtime ($(date)) to $rtc_dev"
		else
			$LOG daemon.error "failed to save localtime to $rtc_dev ($RET)"
		fi
	else
		if [ "$RET" = "0" ]; then
			$LOG daemon.info "set localtime ($(date)) from $rtc_dev"
		else
			$LOG daemon.error "failed to set localtime from $rtc_dev ($RET)"
		fi
	fi
}

systohc() {
	hwclock_call save
}

hctosys() {
	hwclock_call restore
}

start() {
	hwclock_call restore
}

stop() {
	hwclock_call save
}

get_maxtime() {
	local file newest

	for file in $( find /etc -type f ) ; do
		[ -z "$newest" -o "$newest" -ot "$file" ] && newest=$file
	done
	[ "$newest" ] && date -r "$newest" +%s
}
